package com.zhangxiaofanfan.hotcode.fourth.third;

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-05-24 10:33:50
 */
public class HotCode011 {
    public static void main(String[] args) {
        int[] nums = {1,3,-1,-3,5,3,6,7};
        int k = 3;
        HotCode011 hotCode = new HotCode011();
        System.out.println(Arrays.toString(hotCode.maxSlidingWindow(nums, k)));
    }

    public int[] maxSlidingWindow(int[] nums, int k) {
        if (k == 1) {
            return nums;
        }
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < k; i++) {
            while (!deque.isEmpty() && nums[i] > nums[deque.getLast()]) {
                deque.removeLast();
            }
            deque.addLast(i);
        }
        int[] res = new int[nums.length - k + 1];
        res[0] = nums[deque.getFirst()];
        for (int i = k; i < nums.length; i++) {
            while (!deque.isEmpty() && nums[i] > nums[deque.getLast()]) {
                deque.removeLast();
            }
            deque.addLast(i);
            while (deque.getFirst() <= i - k) deque.removeFirst();
            res[i - k + 1] = nums[deque.getFirst()];
        }
        return res;
    }
}
